namespace HZY.Shared.Admin.Extensions;

public static class PagingViewExtensions
{
    /// <summary>
    /// 创建数据源
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="pagingView"></param>
    /// <param name="data"></param>
    /// <param name="mainTableEntityType"></param>
    public static PagingView BuilderDataSource<TEntity>(this PagingView pagingView, List<TEntity> data,
        Type mainTableEntityType)
    {
        pagingView.SetMainTableEntityType(mainTableEntityType);
        var propertyInfos = typeof(TEntity).GetProperties();
        var fieldNames = propertyInfos.Select(item => item.Name).ToList();

        var result = new List<Dictionary<string, object?>>();
        foreach (var item in data)
        {
            var type = item!.GetType();
            var dictionary = new Dictionary<string, object?>();

            foreach (var fieldName in fieldNames)
            {
                dictionary[fieldName] = type?.GetProperty(fieldName)?.GetValue(item);
            }

            result.Add(dictionary);
        }

        pagingView.DataSource = result;

        foreach (var item in fieldNames)
        {
            if (item.StartsWith("_")) continue;
            pagingView.Columns.Add(new TableColumnView(item.ToFirstCharConvertLower(), item));
        }

        return pagingView;
    }

    /// <summary>
    /// 创建数据源 根据 datatable
    /// </summary>
    /// <param name="pagingView"></param>
    /// <param name="data"></param>
    /// <param name="mainTableEntityType"></param>
    public static PagingView BuilderDataSourceByDataTable(this PagingView pagingView, DataTable data,
        Type mainTableEntityType)
    {
        pagingView.SetMainTableEntityType(mainTableEntityType);

        var fieldNames = (from DataColumn dc in data.Columns select dc.ColumnName).ToList();

        var result = new List<Dictionary<string, object?>>();
        foreach (DataRow dr in data.Rows)
        {
            var dictionary = new Dictionary<string, object?>();
            foreach (DataColumn dc in data.Columns)
            {
                dictionary.Add(dc.ColumnName, dr[dc.ColumnName]);
            }

            result.Add(dictionary);
        }

        pagingView.DataSource = result;

        foreach (var item in fieldNames)
        {
            if (item.StartsWith("_")) continue;
            pagingView.Columns.Add(new TableColumnView(item.ToFirstCharConvertLower(), item));
        }

        return pagingView;
    }

    /// <summary>
    /// 获取指定列
    /// </summary>
    /// <param name="pagingView"></param>
    /// <param name="query"></param>
    /// <param name="queryField"></param>
    /// <typeparam name="TQuery"></typeparam>
    /// <returns></returns>
    public static TableColumnView GetColumn<TQuery>(this PagingView pagingView, IQueryable<TQuery> query,
        Expression<Func<TQuery, object>> queryField)
    {
        var nameQuery = Tools.GetNameByExpression(queryField);
        var tableColumnView = pagingView.Columns
            .FirstOrDefault(w => w.FieldName.ToLower() == nameQuery.ToLower());

        return tableColumnView!;
    }

    /// <summary>
    /// 格式化值
    /// </summary>
    /// <typeparam name="TQuery"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="query"></param>
    /// <param name="queryField"></param>
    /// <param name="funcValue"></param>
    public static PagingView FormatValue<TQuery, TValue>(this PagingView pagingView, IQueryable<TQuery> query,
        Expression<Func<TQuery, TValue>> queryField,
        Func<TValue?, object?> funcValue)
    {
        var nameQuery = Tools.GetNameByExpression(queryField);
        foreach (var item in pagingView.DataSource.Where(w => w.ContainsKey(nameQuery)))
        {
            var value = item[nameQuery];
            item[nameQuery] = funcValue?.Invoke(value == null ? default : (TValue)value ?? default);
        }

        return pagingView;
    }

    /// <summary>
    /// 设置列显示名称
    /// </summary>
    /// <returns></returns>
    public static PagingView SetColumnDisplayName(this PagingView pagingView)
    {
        // 设置列显示名称
        using var scope = App.CreateScope();
        var databaseTableService = scope?.ServiceProvider.GetService<IDatabaseTableService>();
        if (databaseTableService == null)
        {
            return pagingView;
        }

        var genDbTableDtos = databaseTableService!.GetAllTablesByCache();

        if (genDbTableDtos.Count == 0)
        {
            return pagingView;
        }

        var table = genDbTableDtos?
            .Where(w => w.EntityName.ToLower() == pagingView.MainTableEntityType?.Name.ToLower())
            .FirstOrDefault();
        if (table == null)
        {
            return pagingView;
        }

        foreach (var column in pagingView.Columns)
        {
            var fieldName = column.FieldName.ToLower();
            var tableInfo = table?.TableInfos?.FirstOrDefault(w => w.ColumnName.ToLower() == fieldName);
            column.Title = string.IsNullOrWhiteSpace(tableInfo?.DisplayName) ? fieldName : tableInfo.DisplayName;
        }

        return pagingView;
    }


    /// <summary>
    /// 设置列信息 用于外键表列头得显示名称
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="tableColumnView"></param>
    /// <param name="field"></param>
    /// <param name="show"></param>
    /// <param name="width"></param>
    /// <param name="sort"></param>
    /// <returns></returns>
    public static TableColumnView SetColumn<TEntity>(this TableColumnView tableColumnView,
        Expression<Func<TEntity, object>> field, bool? show = null, string? width = null, bool sort = true)
    {
        // 设置列显示名称
        using var scope = App.CreateScope();
        var databaseTableService = scope?.ServiceProvider.GetService<IDatabaseTableService>();
        if (databaseTableService == null)
        {
            return tableColumnView;
        }

        var genDbTableDtoList = databaseTableService!.GetAllTablesByCache();
        if (genDbTableDtoList.Count == 0)
        {
            return tableColumnView;
        }

        //自动获取名称对应的显示名称
        var type = typeof(TEntity);
        var name = Tools.GetNameByExpression(field);

        var table = genDbTableDtoList.FirstOrDefault(w => w.EntityName?.ToLower() == type.Name.ToLower());
        if (table == null)
        {
            return tableColumnView;
        }

        var tableInfo = table.TableInfos.FirstOrDefault(w => w.CsField?.ToLower() == name.ToLower());
        if (tableInfo == null)
        {
            return tableColumnView;
        }

        tableColumnView.SetColumn(tableInfo.DisplayName, show, width, sort);

        return tableColumnView;
    }
}